<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mprize extends CI_Model{
    
    //获取奖项
    public function GetPrizes(){
        $query = $this->db->query('select id,prize,jifen,v from wtt_prizes order by id asc');
        return  $query->result_array();
    }
    
    public function EditPrizes()
    {
       $arr_id = $this->input->post('id');
       $arr_prize = $this->input->post('prize');
       $arr_jifen = $this->input->post('jifen');
       $arr_v = $this->input->post('v');
       $DB1 = $this->load->database('update', TRUE);
       foreach($arr_id as $key => $var)
       {
            $DB1->query("update wtt_prizes set prize='".$arr_prize[$key]."',jifen=".$arr_jifen[$key].",v=".$arr_v[$key]." where id=".$var);
       }
       return true;
       
    }
    //获取奖池及状态
    public function GetPrizest()
    {
    	$query = $this->db->query('select jifen,sjifen,isopen from wtt_setp');
    	return $query->row_array();
    }
    //获取中奖列表
    function GetPrizeList($num)
    {
    	$query = $this->db->query('select wb_id,jifen,screen_name,datetime from wtt_gprize order by datetime desc limit 0,'.$num);
    	return $query->result_array();
    }
    //获取抽奖结果
    public function GetPrize($uid,$screen_name)
    {
       $DB1 = $this->load->database('update', TRUE);
        $arr_r = array(
        		'error_info' => '',
        		'info' => ''
        		);
        //及时获取用户积分
        $this->load->model('Mwbuser');
        //进行积分比较，少于30积分提醒积分不足
        $uinfo = $this->Mwbuser->getinfo($uid,'jifen');
        if($uinfo['jifen'] < 30) 
        {
        	$arr_r['error_info'] = '您的积分不足30，不能进行抽奖！';
        	return $arr_r;
        }
        //获取奖项列表
        $p_list = $this->GetPrizes();
        //扣出抽奖积分
        //$this->load->model('Mwbuser');
        $this->Mwbuser->setpoints($uid,30,2);
        $this->Mwbuser->insertlog($uid,0,$screen_name,9,30,0,2,0);
        //写入总奖池
        $DB1->query('update wtt_setp set jifen=jifen+30');
        //获取抽奖结果
        $r_prize = $this->weightedRandom($p_list,'id','v');
    	foreach ($r_prize as $item)
    	{
    		$prize = $item['prize'];
    		$jifens = $item['jifen'];
    	}
    	if($jifens == 0){
    		$arr_r['info'] = '没有中奖，下次继续加油！';
    	}else{
    		$arr_r['info'] = '恭喜您中了'.$prize.'获得'.$jifens.'积分。';
    		$this->insertlog($uid, $screen_name, $jifens);
    		
    	}
    	//总奖池扣除中奖积分
        
    	$DB1->query('update wtt_setp set jifen=jifen-'.$jifens);
    	return $arr_r;
    }
    
    //写入抽奖列表
    private function insertlog($uid,$screen_name,$jifen)
    {
    	$DB1 = $this->load->database('update', TRUE);
        $data = array(
    			'wb_id'=>$uid,
    			'screen_name' => $screen_name,
    			'jifen' => $jifen,
    			'datetime' => time()
    			);
    	$DB1->insert('wtt_gprize',$data);
    	//写入系统收入日志
    	$this->load->model('Mwbuser');
    	$this->Mwbuser->setpoints($uid,$jifen,1);
    	$this->Mwbuser->insertlog($uid,0,$screen_name,9,$jifen,0,1,0);
    	//删除3天前的中奖纪录
    	$deltime = time()-259200;
    	$DB1->query('delete from wtt_gprize where datetime<'.$deltime);
    }
    //根据权重随机读取
    private function weightedRandom(array $arr, $key, $weightKey) {
    $rawArr = array();
    foreach ($arr as $k => $v) {
        $rawArr[$v[$key]] = $v[$weightKey];
    }
    $num = 1;
    $cnt = count($rawArr);
    $ret = array();
    //The first m items of V are inserted into $ret
    $ret = array_slice($rawArr, 0, $num, true);
    $remain = array_slice($rawArr, $num,$cnt-$num, true);
    //For each item vi 2 R: Calculate a key ki = u(1/wi)i , where ui = random (0,1)
    $kArr = array();
    foreach ($ret as $k => $v) {
        srand();
        $u = mt_rand();
        $u = $u / mt_getrandmax();
        $kArr[$k] = pow($u, 1 / $v) ;
    }
    foreach ($remain as $k => $v) {
        //The smallest key in R is the current threshold T
        asort($kArr);
        list($tk, $tv) = each($kArr);
        reset($kArr);
        //For item vi: Calculate a key ki = u(1/wi)i , where ui = random (0,1)
        srand();
        $u = mt_rand();
        $u = $u / mt_getrandmax();
        $ki = pow($u, 1/$v);
        if ($ki > $tv) {
            //replace
            foreach ($ret as $rk => $rv) {
                if ($rk == $tk) {
                    unset($ret[$rk]);
                    $ret[$k] = $v;
                    break;
                };
            }
            unset($kArr[$tk]);
            $kArr[$k] = $ki;
        }
    }
  
    $newItemArr = array();
    foreach ($arr as $k => $v) {
        $newItemArr[$v[$key]] = $v;
    }
    $ret = array_intersect_key($newItemArr, $ret);
    return $ret;
}
}